package com.sogoodsoft.service.common;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Properties;
import java.util.StringTokenizer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Component;

import com.sogoodsoft.entity.account.User;
import com.sogoodsoft.entity.app.SysClass;
import com.sogoodsoft.entity.common.Maillog;
import com.sogoodsoft.entity.project.Assessment;
import com.sogoodsoft.service.app.SysClassService;
import com.sogoodsoft.util.InfosysSecurityUtil;

/**
 * 通信服务
 * 
 * @author LXZ
 * 
 */
/**
 * @author Administrator
 *
 */
@Component
public class CommunicateService {
	protected Logger logger = LoggerFactory.getLogger(getClass());
	private static String smtp;
	private static String mailAccount;
	private static String mailPassword;
	private static String mailFrom;
	private static JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
	private static String SMSURL;
	private static boolean load = false;
	private SysClassService sysSer;
	private MaillogService mailSer;
	private SmslogService smsSer;	
	private static SysClass faild;
	private static SysClass succ ;
	private static User user ;

	public boolean sendMail(Assessment assessment,String subject, String mail, String... mailBox) {
		boolean success = true;

		init();

		// 建立邮件消息
		SimpleMailMessage mailMessage = new SimpleMailMessage();
		// 设置收件人，寄件人 用数组发送多个邮件
		// String[] array = new String[] {"sun111@163.com","sun222@sohu.com"};
		// mailMessage.setTo(array);
		mailMessage.setTo(mailBox);
		mailMessage.setFrom(mailFrom);
		mailMessage.setSubject(subject);
		mailMessage.setText(mail);
		try{
			senderImpl.send(mailMessage);
			for(int i=0; i<mailBox.length;i++){
				Maillog maillog = new Maillog();
				maillog.setMail(mail);
				maillog.setMailFrom(mailFrom);
				maillog.setMailTime(new Date());
				maillog.setMailTo(mailBox[i]);
				maillog.setSubject(subject);
				maillog.setSysClass(succ);
				user = InfosysSecurityUtil.getCurrentUser();
				maillog.setUser(user);
				maillog.setAssId(assessment.getId());
				mailSer.save(maillog);
			
			}
		}catch(Exception e){
			for(int i=0; i<mailBox.length;i++){
				Maillog maillog = new Maillog();
				maillog.setMail(mail);
				maillog.setMailFrom(mailFrom);
				maillog.setMailTime(new Date());
				maillog.setMailTo(mailBox[i]);
				maillog.setSubject(subject);
				maillog.setSysClass(faild);
				user = InfosysSecurityUtil.getCurrentUser();
				maillog.setUser(user);
				maillog.setAssId(assessment.getId());
				mailSer.save(maillog);
			}
		}
		return success;
	}

	public boolean sendSMS(String msg, String phone) {
		init();
		boolean success = false;

		try {
			String surl = new String(SMSURL);
			String content = URLEncoder.encode(msg,"GBK");
			surl = surl.replace("$content$", content);			
			surl = surl.replace("$phone$", phone);

		
//			URL url = new URL(surl);
//			logger.debug(url.toString());
//			HttpURLConnection connect = (HttpURLConnection)url.openConnection();
//			BufferedReader in = new BufferedReader(new InputStreamReader(connect.getInputStream()));
//
//			// 返回发送结果
//			String inputline = in.readLine();
//			in.close();
//
//			if("-1".equals(inputline)){				
//				logger.debug("短信发送失败");
//				logger.debug("返回值："+inputline);
//				success = false;
//				
//			}else{
//				success = true;
//				logger.debug("短信发送成功！");
//				
//			}
		} catch (Exception e) {
			success = false;
			e.printStackTrace();
		}
		
		return success;
	}

	public void init() {
		if(load)return;
		SMSURL = sysSer.getByCode("COMM_SMS_URL").getNote();
		String mailCfg = sysSer.getByCode("COMM_MAIL_CFG").getNote();
		StringTokenizer token = new StringTokenizer(mailCfg, "$");
		String name;
		String value;
		String tmp[];
		while (token.hasMoreElements()) {
			name = token.nextToken();
			logger.debug("token=" + name);
			tmp = name.split(":");
			name = tmp[0];
			logger.debug("name=" + name);
			value = tmp[1];
			logger.debug("value=" + value);
			

			if (name.indexOf("SMPT") >= 0) {
				smtp = value;
				logger.debug("smtp=" + smtp);
			}

			if (name.indexOf("ACCOUNT") >= 0) {
				mailAccount = value;
				logger.debug("account=" + mailAccount);
			}

			if (name.indexOf("PASSWORD") >= 0) {
				mailPassword = value;
				logger.debug("password=" + mailPassword);
			}
			if (name.indexOf("FROM") >= 0) {
				mailFrom = value;
				logger.debug("mailFrom=" + mailFrom);
			}
		}

		senderImpl.setHost(smtp);
		senderImpl.setUsername(mailAccount); // 根据自己的情况,设置username
		senderImpl.setPassword(mailPassword); // 根据自己的情况, 设置password
		Properties prop = new Properties();
		prop.put("mail.smtp.auth", "true"); // 将这个参数设为true，让服务器进行认证,认证用户名和密码是否正确
		prop.put("mail.smtp.timeout", "25000");
		senderImpl.setJavaMailProperties(prop);
		
		faild = sysSer.getByCode("COMM_STATUS_FAILD");
		succ = sysSer.getByCode("COMM_STATUS_SUCCESS");
		load = true;
	}

	public SysClassService getSysSer() {
		return sysSer;
	}

	@Autowired
	public void setSysSer(SysClassService sysSer) {
		this.sysSer = sysSer;
	}

	public MaillogService getMailSer() {
		return mailSer;
	}

	@Autowired
	public void setMailSer(MaillogService mailSer) {
		this.mailSer = mailSer;
	}

	public SmslogService getSmsSer() {
		return smsSer;
	}

	@Autowired
	public void setSmsSer(SmslogService smsSer) {
		this.smsSer = smsSer;
	}
	
}
